<?php
 require "INewsDB.class.php";

 class NewsDB implements INewsDB {
     const DB_NAME = 'c:\xampp\htdocs\php-3\news.db';
     const RSS_NAME = 'rss.xml';
     const RSS_TITLE = 'Новостная лента .';
     const RSS_LINK = 'news.php';
     const RSS_URL = 'rss.xml';
     const FILE_NAME = 'news.xml';
     protected $_db;

     function __construct() {

         if (is_file(self::DB_NAME)) {
             $this->_db = new SQLite3(self::DB_NAME);
         } else {
             $this->_db = new SQLite3(self::DB_NAME);

             $this->create_DB($this->_db);
         }
     }

     public function download() {
         $file = file_get_contents(self::RSS_URL);
         if (!$file)
             return FALSE;

         if (!is_file(self::FILE_NAME)) {
             file_put_contents(self::FILE_NAME, $file);
         } else {
            if (time() > filemtime(self::FILE_NAME) + 60) {
                file_put_contents(self::FILE_NAME, $file);
            }
         }
     }

     public function createRss() {
         $dom = new DOMDocument('1.0', 'utf-8');
         $dom->formatOutput = true;
         $dom->preserveWhiteSpace = false;

         $rss = $dom->createElement("rss");
         $dom->appendChild($rss);
         $version = $dom->createAttribute("version");
         $version->value = "2.0";
         $rss->appendChild($version);

         $channel = $dom->createElement('channel');
         $rss->appendChild($channel);

         $title = $dom->createElement('title', self::RSS_TITLE);
         $link = $dom->createElement('link', self::RSS_LINK);
         $channel->appendChild($title);
         $channel->appendChild($link);

         $news = $this->getNews();
         if (!$news) return FALSE;

         foreach ($news as $value) {
             $item = $dom->createElement('item');
             $channel->appendChild($item);

             $item_title = $dom->createElement('title', $value['title']);
             $t_link = self::RSS_LINK . "?id=" . $value['id'];
             $item_link = $dom->createElement('link', $t_link);
             $item_description = $dom->createElement('description', $value['description']);
             $t_date = date('d-m-Y H-i-s', $value['datetime']);
             $item_pubDate = $dom->createElement('pubDate', $t_date);
             $item_category = $dom->createElement('category', $value['category']);
             $item->appendChild($item_title);
             $item->appendChild($item_link);
             $item->appendChild($item_description);
             $item->appendChild($item_pubDate);
             $item->appendChild($item_category);
         }

         $dom->save(self::RSS_NAME);
     }

     private function create_DB($db) {
         $db->exec("CREATE TABLE msgs (id INTEGER PRIMARY KEY AUTOINCREMENT,
                                                 title TEXT,
                                                 category INTEGER,
                                                 description TEXT,
                                                 source TEXT,
                                                 datetime INTEGER)");

         $db->exec("CREATE TABLE category (id INTEGER,
                                                      name TEXT)");

         $db->exec("INSERT INTO category(id, name)
                               SELECT 1 as id, 'Политика' as name
                               UNION SELECT 2 as id, 'Культура' as name
                               UNION SELECT 3 as id, 'Спорт' as name");
     }

     public function saveNews($title, $category, $description, $source) {
        try {
            $dateTime = time();
            $query = "INSERT INTO msgs(title, category, description, source, datetime)
                  VALUES (:title, :category, :description, :source, :datetime)";
            $stmt = $this->_db->prepare($query);
            if(!$stmt)
                throw new Exception($this->_db->lastErrorMsg());

            $stmt->bindParam(":title", $title, SQLITE3_TEXT);
            $stmt->bindParam(":category", $category, SQLITE3_INTEGER);
            $stmt->bindParam(":description", $description, SQLITE3_TEXT);
            $stmt->bindParam(":source", $source, SQLITE3_TEXT);
            $stmt->bindParam(":datetime", $dateTime, SQLITE3_INTEGER);

            $stmt->execute();
            $stmt->close();

            $this->createRss();
            return TRUE;
        } catch(Exception $e) {
//            $e->getMessage();
            return FALSE;
        }
     }

     protected function db2Array($data) {
         $arr = array();
         while($row = $data->fetchArray(SQLITE3_ASSOC))
             $arr[] = $row;
         return $arr;
     }

     public function getNews() {
       try {
           $query = "SELECT msgs.id as id, msgs.title, category.name as category, msgs.description, msgs.source, msgs.datetime
                FROM msgs, category
                WHERE category.id = msgs.category ORDER BY msgs.id DESC";
           $result = $this->_db->query($query);
           if (!$result)
               throw new Exception($this->_db->lastErrorMsg());

           return $this->db2Array($result);
       } catch(Exception $e) {
//           $e->getMessage();
            return FALSE;
       }
     }

     public function deleteNews($id) {
        try {
            $query = "DELETE FROM msgs WHERE id = ". $id;
            $res = $this->_db->exec($query) or die($this->_db->lastErrorMsg());
            if (!$res)
                throw new Exception($this->_db->lastErrorMsg());
            return TRUE;
        } catch(Exception $e) {
            //$e->getMessage();
            return FALSE;
        }
     }

     function __destruct() {
         unset($this->_db);
     }

     public  function clearStr($str) {
         return $this->_db->escapeString(trim(strip_tags($str)));
     }

     public function clearInt($int) {
         return abs((int)$int);
     }
 }

?>